package com.jt.assistant.ui

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.jt.assistant.R
import com.jt.assistant.adapter.PicPreAdapter
import com.jt.assistant.base.GlobalConfig.PIC_RESULT
import com.yzp.mvvmlibrary.base.BaseActivity
import com.yzp.mvvmlibrary.base.NoViewModel
import kotlinx.android.synthetic.main.activity_pre.*
import java.util.*


class PreActivity : BaseActivity<NoViewModel>() {
    private val mAdapter by lazy {
        PicPreAdapter(
            ArrayList<String>()
        )
    }

    override fun layoutId(): Int = R.layout.activity_pre

    override fun initView(savedInstanceState: Bundle?) {
        with(vp_pic) {
            orientation = ViewPager2.ORIENTATION_HORIZONTAL
            adapter = mAdapter
        }
        if (intent.getBooleanExtra("SKUCHECK", false)) {
            tv_delete.visibility = View.GONE
        }
    }

    override fun initData() {
        top_bar.mIvBack.setOnClickListener {
            val i = Intent()
            i.putExtra(PIC_RESULT, GsonUtils.toJson(mAdapter.data))
            setResult(RESULT_OK, i)
            finish()
        }

        val data = GsonUtils.fromJson<ArrayList<String>>(
            intent.getStringExtra("IMAGEPATH").toString(),
            object : TypeToken<ArrayList<String>>() {}.type
        )


        data.let {
            data.remove("")
            log(it)
            mAdapter.data.addAll(it)
            mAdapter.notifyDataSetChanged()
            vp_pic.setCurrentItem(intent.getIntExtra("POSITION", 0), false)
            vp_pic.offscreenPageLimit = 30
        }
    }

    override fun initListener() {
        tv_delete.setOnClickListener {
            if (mAdapter.data.size > 0) {
                mAdapter.data.remove(mAdapter.data[vp_pic.currentItem])
                mAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            val i = Intent()
            i.putExtra(PIC_RESULT, GsonUtils.toJson(mAdapter.data))
            setResult(RESULT_OK, i)
            finish()
            true
        } else {
            super.onKeyDown(keyCode, event)
        }


}